package com.zz.demo2;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

//GZIP压缩解压缩工具
public abstract class GZipUtils {
    //数据压缩
    public static byte[] compress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 压缩
        compress(bais, baos);
        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();
        return output;
    } //文件压缩

    public static void compress(File file) throws Exception {
        compress(file, true);
    }

    //文件压缩 是否删除原始文件
    public static void compress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream("/opt/log/2018-01-39" + ".gz");
        compress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();
        if (delete) {
            file.delete();
        }
    }
    //多个文件压缩 是否删除原始文件
    public static void compresss(List<File> file, boolean delete) throws Exception {
        FileOutputStream fos = new FileOutputStream("/opt/log/2018-01-32" + ".gz");
        FileInputStream fis = null;
        GZIPOutputStream gos = new GZIPOutputStream(fos);
        for (File fil:file) {
            fis= new FileInputStream(fil);
           // compress(fis, fos);
            int count;
            byte data[] = new byte[1024];
            while ((count = fis.read(data, 0, 1024)) != -1) {
                gos.write(data, 0, count);
            }
            if (delete) {
                fil.delete();
            }
        }
        gos.finish();
        gos.close();
        fis.close();
        fos.flush();
        fos.close();
    }

    //数据压缩
    public static void compress(InputStream is, OutputStream os) throws Exception {
        GZIPOutputStream gos = new GZIPOutputStream(os);
        int count;
        byte data[] = new byte[1024];
        while ((count = is.read(data, 0, 1024)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.flush();
        gos.close();
    }

    //文件压缩  默认删除源文件
    public static void compress(String path) throws Exception {
        compress(path, true);
    } //文件压缩 是否删除原始文件

    public static void compress(String path, boolean delete) throws Exception {
        File file = new File(path);
        compress(file, delete);
    }

    //数据解压缩
    public static byte[] decompress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 解压缩
        decompress(bais, baos);
        data = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();
        return data;
    } //文件解压缩

    public static void decompress(File file) throws Exception {
        decompress(file, true);
    }


    //文件解压缩 是否删除原始文件
    public static void decompress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath().replace(".gz", ""));
        decompress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();
        if (delete) {
            file.delete();
        }
    }

    //数据解压缩
    public static void decompress(InputStream is, OutputStream os) throws Exception {
        GZIPInputStream gis = new GZIPInputStream(is);
        int count;
        byte data[] = new byte[1024];
        while ((count = gis.read(data, 0, 1024)) != -1) {
            os.write(data, 0, count);
        }
        gis.close();
    }

    //文件解压缩 ,默认删除源文件
    public static void decompress(String path) throws Exception {
        decompress(path, true);
    }

    //文件解压缩   是否删除原始文件
    public static void decompress(String path, boolean delete) throws Exception {
        File file = new File(path);
        decompress(file, delete);
    }

    public static void zipFiles(List<File> srcFiles, File zipFile) {
        // 判断压缩后的文件存在不，不存在则创建
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        // 创建 FileInputStream 对象
        FileInputStream fileInputStream = null;

        try {
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFile);
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            // 遍历源文件数组
            for (int i = 0; i < srcFiles.size(); i++) {
                // 将源文件数组中的当前文件读入 FileInputStream 流中
                fileInputStream = new FileInputStream(srcFiles.get(i));
                // 实例化 ZipEntry 对象，源文件数组中的当前文件
                zipEntry = new ZipEntry(srcFiles.get(i).getName());
                zipOutputStream.putNextEntry(zipEntry);
                // 该变量记录每次真正读的字节个数
                int len;
                // 定义每次读取的字节数组
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static File pack(List<File> sources, File target) throws IOException {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(target);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        TarArchiveOutputStream os = new TarArchiveOutputStream(out);
        for (File file : sources) {
            InputStream inputStream = null;

            try {
                os.putArchiveEntry(new TarArchiveEntry(file,file.getName()));//打包的时候只是包含文件，不带路径
                //os.putArchiveEntry(new TarArchiveEntry(file));  //打包的时候带路径
                inputStream = new FileInputStream(file);
                IOUtils.copy(inputStream, os);
                os.closeArchiveEntry();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            file.delete();
        }
        if (os != null) {
            try {
                os.flush();
                os.close();
                System.out.println("打包后文件为：" + target);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return target;
    }


    /**
     * tar打包压缩
     * @param source  需要压缩的文件
     * @param FilePath  压缩后的文件全文件名(.tar)
     * @return  返回压缩后的文件
     */
    public static File compress(File source,String FilePath) {
        File target = new File(FilePath);
        FileInputStream in = null;
        GZIPOutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new GZIPOutputStream(new FileOutputStream(target));
            byte[] array = new byte[1024];
            int number;
            while ((number = in.read(array, 0, array.length)) != -1) {
                out.write(array, 0, number);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                    source.delete();//解压成功后，删除tar文件
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
            if (out != null) {
                try {
                    out.close();
                    System.out.println("打包后文件为：" + target);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return target;
    }

    public static void main(String[] args) throws Exception {
        File file = new File("/opt/log");
        File[] files = file.listFiles();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //huoquqianyitianriqi
        /*Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE,-1);
        String format = dateFormat.format(ca.getTime());*/
        String format = dateFormat.format(new Date());
        List<File> file1 = new ArrayList<>();
        for (File filel:files) {
            String[] split = filel.getName().split("\\.");
            //System.out.println(split[2]);
            if (split.length==5 && format.equals(split[2])) {
                file1.add(filel);
            }
        }
        File file2 = pack(file1,new File("/opt/log/2018-03.tar"));
        compress(file2,"/opt/log/2018-03.tar.gz");

    }
}
